package com.cinema.util;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

/**
 * 文件上传工具类
 */
public class FileUploadUtil {
    
    // 项目根目录路径
    private static final String PROJECT_ROOT = "D:\\project\\java\\cinema-booking-system\\src\\main\\webapp";
    
    // 图片上传目录
    private static final String IMAGES_DIR = "images";
    private static final String MOVIES_DIR = "movies";
    private static final String AVATARS_DIR = "avatars";
    
    /**
     * 获取项目根目录路径
     */
    public static String getProjectRoot() {
        return PROJECT_ROOT;
    }
    
    /**
     * 获取图片根目录路径
     */
    public static String getImagesPath() {
        return PROJECT_ROOT + File.separator + IMAGES_DIR;
    }
    
    /**
     * 获取电影图片目录路径
     */
    public static String getMoviesPath() {
        return getImagesPath() + File.separator + MOVIES_DIR;
    }
    
    /**
     * 获取头像目录路径
     */
    public static String getAvatarsPath() {
        return getImagesPath() + File.separator + AVATARS_DIR;
    }
    
    /**
     * 确保目录存在，如果不存在则创建
     */
    public static boolean ensureDirectoryExists(String dirPath) {
        try {
            Path path = Paths.get(dirPath);
            if (!Files.exists(path)) {
                Files.createDirectories(path);
                System.out.println("创建目录: " + dirPath);
                return true;
            }
            return true;
        } catch (IOException e) {
            System.err.println("创建目录失败: " + dirPath + ", 错误: " + e.getMessage());
            return false;
        }
    }
    
    /**
     * 初始化所有必要的目录
     */
    public static void initializeDirectories() {
        System.out.println("初始化文件上传目录...");
        System.out.println("项目根目录: " + PROJECT_ROOT);
        
        // 创建基础目录
        ensureDirectoryExists(getImagesPath());
        ensureDirectoryExists(getMoviesPath());
        ensureDirectoryExists(getAvatarsPath());
        
        // 检查默认图片
        checkDefaultImages();
        
        System.out.println("文件上传目录初始化完成");
    }
    
    /**
     * 检查默认图片是否存在
     */
    private static void checkDefaultImages() {
        String defaultPosterPath = getImagesPath() + File.separator + "default-poster.jpg";
        String defaultAvatarPath = getImagesPath() + File.separator + "default-avatar.jpg";
        
        // 检查默认海报是否存在
        if (!Files.exists(Paths.get(defaultPosterPath))) {
            System.out.println("注意: 默认海报图片不存在: " + defaultPosterPath);
            System.out.println("建议添加默认海报图片到该路径");
        }
        
        // 检查默认头像是否存在
        if (!Files.exists(Paths.get(defaultAvatarPath))) {
            System.out.println("注意: 默认头像图片不存在: " + defaultAvatarPath);
            System.out.println("建议添加默认头像图片到该路径");
        }
    }
    
    /**
     * 生成唯一文件名
     */
    public static String generateUniqueFileName(String originalFileName) {
        String extension = getFileExtension(originalFileName);
        return UUID.randomUUID().toString() + extension;
    }
    
    /**
     * 获取文件扩展名
     */
    public static String getFileExtension(String fileName) {
        if (fileName == null || fileName.trim().isEmpty()) {
            return "";
        }
        
        int lastDotIndex = fileName.lastIndexOf('.');
        if (lastDotIndex > 0 && lastDotIndex < fileName.length() - 1) {
            return fileName.substring(lastDotIndex);
        }
        return "";
    }
    
    /**
     * 验证文件类型是否为图片
     */
    public static boolean isValidImageType(String contentType) {
        return contentType != null && (
            contentType.equals("image/jpeg") ||
            contentType.equals("image/jpg") ||
            contentType.equals("image/png") ||
            contentType.equals("image/gif") ||
            contentType.equals("image/webp")
        );
    }
    
    /**
     * 验证文件扩展名是否为图片
     */
    public static boolean isValidImageExtension(String fileName) {
        if (fileName == null) return false;
        
        String extension = getFileExtension(fileName).toLowerCase();
        return extension.equals(".jpg") || 
               extension.equals(".jpeg") || 
               extension.equals(".png") || 
               extension.equals(".gif") || 
               extension.equals(".webp");
    }
    
    /**
     * 检查文件大小是否在允许范围内
     */
    public static boolean isValidFileSize(long fileSize, long maxSizeInBytes) {
        return fileSize > 0 && fileSize <= maxSizeInBytes;
    }
    
    /**
     * 格式化文件大小显示
     */
    public static String formatFileSize(long bytes) {
        if (bytes < 1024) {
            return bytes + " B";
        } else if (bytes < 1024 * 1024) {
            return String.format("%.1f KB", bytes / 1024.0);
        } else if (bytes < 1024 * 1024 * 1024) {
            return String.format("%.1f MB", bytes / (1024.0 * 1024.0));
        } else {
            return String.format("%.1f GB", bytes / (1024.0 * 1024.0 * 1024.0));
        }
    }
    
    /**
     * 清理文件名，移除特殊字符
     */
    public static String sanitizeFileName(String fileName) {
        if (fileName == null || fileName.trim().isEmpty()) {
            return "unnamed";
        }
        
        // 移除或替换特殊字符
        return fileName.replaceAll("[^a-zA-Z0-9\\.\\-_]", "_");
    }
    
    /**
     * 获取文件的Web访问URL
     */
    public static String getWebUrl(String contextPath, String relativePath) {
        // 移除开头的斜杠（如果有）
        if (relativePath.startsWith("/")) {
            relativePath = relativePath.substring(1);
        }
        
        // 确保路径以images开头
        if (!relativePath.startsWith("images/")) {
            relativePath = "images/" + relativePath;
        }
        
        return contextPath + "/" + relativePath;
    }
    
    /**
     * 删除文件
     */
    public static boolean deleteFile(String filePath) {
        try {
            Path path = Paths.get(filePath);
            if (Files.exists(path)) {
                Files.delete(path);
                System.out.println("删除文件: " + filePath);
                return true;
            }
            return false;
        } catch (IOException e) {
            System.err.println("删除文件失败: " + filePath + ", 错误: " + e.getMessage());
            return false;
        }
    }
    
    /**
     * 获取文件名（不包含路径）
     */
    public static String getFileName(String filePath) {
        if (filePath == null || filePath.trim().isEmpty()) {
            return "";
        }
        
        // 处理Windows和Unix路径分隔符
        int lastSlashIndex = Math.max(filePath.lastIndexOf('/'), filePath.lastIndexOf('\\'));
        if (lastSlashIndex >= 0 && lastSlashIndex < filePath.length() - 1) {
            return filePath.substring(lastSlashIndex + 1);
        }
        return filePath;
    }
    
    /**
     * 检查文件是否存在
     */
    public static boolean fileExists(String filePath) {
        return Files.exists(Paths.get(filePath));
    }
    
    /**
     * 获取文件大小
     */
    public static long getFileSize(String filePath) {
        try {
            return Files.size(Paths.get(filePath));
        } catch (IOException e) {
            return 0;
        }
    }
}
